package com.tonysong.ssm.controller;

import com.tonysong.ssm.pojo.User;
import com.tonysong.ssm.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author 宋伟宁
 * @Date 2023/9/19
 * @Version 1.0
 **/
@Controller
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    @RequestMapping("/list")
    public String list(Model model,
                       @RequestParam(name = "offset",defaultValue = "1")Integer offset,
                       @RequestParam(name = "pageSize",defaultValue = "3")Integer pageSize){
        model.addAttribute("pager",this.userService.getPageInfo(offset,pageSize));
        return "list";
    }
    @GetMapping("/add")
    public String toadd(){
        return "add";
    }

    @PostMapping("/add")
    public String add( User user){
        System.out.println(user);
         this.userService.save(user);
//         return "list";

         return "redirect:/list";
//        return UrlBasedViewResolver.REDIRECT_URL_PREFIX+"/list";
    }

    @GetMapping("/update")
    public String show(Integer id,Model model){
        System.out.println(id);
//        User user = this.userService.findById(id);
//        model.addAttribute("user",user);
        model.addAttribute(this.userService.findById(id));
        return "update";
    }
    @PostMapping("/update")
    public String update(User user){
        System.out.println("#############################");
        this.userService.save(user);
        return "redirect:/list";
    }



    @GetMapping("/login")
    public String tologin(){
        return "login";
    }
    @PostMapping("/login")
    public String login(User user,HttpSession session,Model model){
        User login = this.userService.login(user);
        if(login!=null){
            session.setAttribute("logUser",login);
            return "redirect:/list";
        }else{
            model.addAttribute("msg","<font>对不起，登录失败！</font>");
            return "login";
        }


    }
}
